
/**
   * Created by PanJiaChen on 16/11/18.
   */

/**
   * Parse the time to string
   * @param {(Object|string|number)} time
   * @param {string} cFormat
   * @returns {string}
   */
export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
   * @param {number} time
   * @param {string} option
   * @returns {string}
   */
export function formatTime (time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
   * @param {string} url
   * @returns {Object}
   */
export function param2Obj (url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, ' ') +
    '"}'
  )
}

/**
   * @description 检测是否是数组
   * @param {(Array)} array
   * @returns {Boolean}
   */
export function isArray (array) {
  return Object.prototype.toString.call(array) === '[object Array]'
}

/**
   * @description 从Array获取字典
   * @param {(Array)} array
   * @param {string} key
   * @returns {Object}
   */
export function getMap (array, key) {
  var returnMap = {}
  if (isArray(array)) {
    for (var i = 0; i < array.length; i++) {
      var item = array[i]
      returnMap[item[key]] = item
    }
  }
  return returnMap
}

// 获得数组的纯key字段数组
export function getKeyStringArray (array, key) {
  if (!isArray(array)) return []
  var newArray = []
  for (var i = 0; i < array.length; i++) {
    newArray.push(array[i][key])
  }
  return newArray
}
/**
 * @description 数组添加删除值方法
 *
 * @param {string} val 要对比相等的值
 * @param {string} keyname 对应key名字（对象数组）
 * @returns {Array}
 */
export function removeByValue (array, val, keyname) {
  // debugger
  for (var i = 0; i < array.length; i++) {
    if (keyname) {
      if (array[i][keyname] == val) {
        array.splice(i, 1)
        break
      }
    } else {
      if (array[i] == val) {
        array.splice(i, 1)
        break
      }
    }
  }
}

// 数组添加判断某对象是否在其中，存在返回其索引和true，否则返回false
export function objInArray (array, key, value) {
  // JSON.stringify(cfg.inputs).indexOf(JSON.stringify(taskNameObj)) != -1
  for (var i = 0; i < array.length; i++) {
    console.log(array[i][key])
    if (typeof (array[i]) === 'object' && array[i][key].indexOf(value) > -1) { return { result: true, index: i } }
  }
  return false
}

// 通过索引删除某项
export function removeByIndex (array, index) {
  array.splice(index, 1)
}

// 通过某值删除某项，针对普通元素类型的数组
export function removeByVal (array, val) {
  var index = array.indexOf(val)
  if (index > -1) {
    array.splice(index, 1)
  }
}

// 是否在数组里存在 数组：对象的合集
// key：数组里某对象的k属性  search：搜索的某字符串（要对应对象k属性的值相等）
// rtindex:true 存在的时候返回索引 false 存在的时候返回true
export function isInArrayByKeySearchVal (array, key, search, rtindex) {
  if (!isArray(array)) return false
  for (var i in array) {
    if (array[i] && array[i][key] == search) {
      if (rtindex) return i
      else return true
    }
  }
  if (rtindex) return -1
  else return false
}
// 是否在数组里存在 数组：字符串的合集
// search：搜索的某字符串
export function isInArrayBySearchVal (array, search, rtindex) {
  if (!isArray(array)) return false
  for (var i in array) {
    if (array[i] == search) {
      if (rtindex) return i
      else return true
    }
  }
  if (rtindex) return -1
  else return false
}

// 返回一个新的数据 不影响旧数据
export function getNewData (data) {
  if (data == undefined) return data
  return JSON.parse(JSON.stringify(data))
}

// 返回一个JSON.parse(string)对象 报错时设置为defaultVal
export function getObjByString (string, defaultVal) {
  var result = string
  if (typeof (result) === 'string') {
    try {
      result = JSON.parse(result)
      if (!result) result = defaultVal || {}
    } catch (e) {
      result = defaultVal || {}
    }
  }
  return result
}

// 获取url参数
export function getQueryString (name) { // decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return decodeURI(r[2]); return null
}

export function setDataBySession (name, val) {
  sessionStorage.setItem(name, val)
}

export function getDataBySession (name) {
  return sessionStorage.getItem(name)
}

export function delDataBySession (name) {
  sessionStorage.removeItem(name)
}

export function getDataByLocal (name) {
  return localStorage.getItem(name)
}

export function setDataByLocal (name, val) {
  localStorage.setItem(name, val)
}
